package state.util;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.VolumeControl;

import development.Global;

import state.GameGlobal;

public class SoundAndVibrateUtil implements PlayerListener {
	public static boolean isVibrate;
	public static int volume  = 50; // 0 ~ 100;
	public static Player player;
	private static InputStream is;
	
	public static void play(String fileName) {
		if (player != null) {
			try {
				player.stop();
			} catch (MediaException e) {
			}
			player = null;
		}
		
		is = GameGlobal.class.getResourceAsStream(fileName);
		try {
			player = Manager.createPlayer(is, "audio/midi");
			player.prefetch();
			((VolumeControl) player.getControl("VolumeControl")).setLevel(volume);
			player.start();
		} catch (Throwable e) {
		  if (player != null) {
		    player.close();
		  }
		  if (is != null) {
		    try {
          is.close();
        } catch (IOException e1) {
        }
		  }
			System.out.println("MEDIA ERROR: " + fileName);
			if (Global.systemCanvas.isDebugMode()) {
        e.printStackTrace();
      }
		}
	}

  public void playerUpdate(Player player, String event, Object eventData) {
    if (event.equals(PlayerListener.END_OF_MEDIA)) {
      if (is != null) {
        try {
          is.close();
        } catch (IOException e) {
        }
      }
      
      if (player != null) {
        try {
          player.stop();
        } catch (MediaException e) {
        }
        player = null;
      }
    }
  }
}
